﻿using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    public class CADPrintOrderInfoController : BuyiController
    {
        [HttpPost, Route("cadprint")]
        public HttpResponseMessage PrintOrderInfo(string orderName)
        {
            try
            {
                string sql = " select id,state,erp_custname,finish_time,erp_name,mColor,mCode from Order_tb where name=@name";
                SQLCommand sc = new SQLCommand(sql, "@name", orderName);
                DataRow dr = sc.ExecuteOneRow();
                if (dr == null)
                    return AssistFun.toJson(new { status = 201, tip = "没有找到此订单", data = "" });
                int OrderId = Convert.ToInt32(dr["id"]);
                int State = Convert.ToInt32(dr["state"]);
                DateTime finish = Convert.ToDateTime(dr["finish_time"]);
                string customerName = Convert.ToString(dr["erp_custname"]);
                string erpName = Convert.ToString(dr["erp_name"]);
                string mColor = Convert.ToString(dr["mColor"]);
                string mcode = Convert.ToString(dr["mCode"]);

                string xmlPath = null;
                if (State == 0)
                    return AssistFun.toJson(new { status = 201, tip = "生产单已废弃", data = "" });

                if (State == 1)
                    xmlPath = GetPCPath(orderName) + "\\" + orderName + ".xml";
                if (State == 2)
                    xmlPath = this.GetOrderFile(OrderId, ".xml");
                if (xmlPath == null)
                    return AssistFun.toJson(new { status = 201, tip = "找不到文件", data = "" });
                WriteDebug("PrintOrderInfo", "XML路径：" + xmlPath);

                XmlDocument doc = new XmlDocument();
                doc.Load(xmlPath);
                td tt = null;
                using (StringReader rdr = new StringReader(doc.InnerXml))
                {
                    //声明序列化对象实例serializer   
                    XmlSerializer serializer = new XmlSerializer(typeof(td));
                    //反序列化，并将反序列化结果值赋给变量tt  
                    tt = (td)serializer.Deserialize(rdr);
                }
                //流水号匹配 
                List<PersonLsh> personList = MathLSH(tt.personList, OrderId);
                if (personList.Count > 0)
                    return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = personList.Count, rows = new { orderinfo = new Models.CADModel.OrderInfo(erpName, mcode, mColor, customerName, finish), personList = personList.OrderBy(p => p.LSH), measureName = tt.measureName } } });
                else
                    return AssistFun.toJson(new { status = 201, tip = "量体没有对应的流水号信息", data = "" });
            }
            catch (Exception ex)
            {
                WriteDebug("PrintOrderInfo", "异常：" + ex.Message);
                return AssistFun.toJson(new { status = 201, tip = ex.Message, data = "" });
            }
        }

        /// <summary> 
        /// 流水号匹配 
        /// </summary> 
        /// <param name="personList"></param>
        /// <param name="id">订单id</param>
        private List<PersonLsh> MathLSH(List<person> personList, int id)
        {
            string sql = "select erp_id,LSH from LSH_tb where order_id=@orderid";
            SQLCommand sc = new SQLCommand(sql, "@orderid", id);
            DataTable dt = sc.ExecuteScalars();
            //获取特体  
            sql = "select distinct Pod_tb.pod from Pod_tb inner join LSH_tb on Pod_tb.order_id = LSH_tb.order_id and Pod_tb.pod = LSH_tb.pod where Pod_tb.order_id = @orderid";
            sc = new SQLCommand(sql, "@orderid", id);
            DataTable pods = sc.ExecuteScalars();

            List<LSHInfo> lshList = new List<LSHInfo>();
            List<PersonLsh> personLshs = new List<PersonLsh>();
            if (dt == null)
                return personLshs;
            else
            {
                List<int> allPod = new List<int>();
                if (pods != null)
                    allPod = pods.AsEnumerable().Select(d => d.Field<int>("pod")).ToList();
                lshList = AssistFun.DataTableToList<LSHInfo>(dt);
                foreach (LSHInfo lsh in lshList)
                {

                    foreach (person per in personList)
                    {
                        if (lsh.erp_id == per.ID)
                        {
                            PersonLsh perlsh = null;
                            if (allPod.Exists(o => o.Equals(per.pod)))
                                perlsh = new PersonLsh(per, lsh.LSH, true);
                            else
                                perlsh = new PersonLsh(per, lsh.LSH);
                            personLshs.Add(perlsh);
                            break;
                        }
                    }
                }
            }
            return personLshs;
        }


    }
   
}
